<template>
  <div class="award-step">
    <div class="step-header">
      <h3>获奖经历</h3>
      <p>请填写您的获奖证书和荣誉</p>
    </div>

    <div class="award-list">
      <div
        v-for="(award, index) in awardList"
        :key="award.id || index"
        class="award-item"
      >
        <el-form
          :model="award"
          :rules="rules"
          label-width="100px"
          class="award-form"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="奖项名称" prop="award_name">
                <el-input v-model="award.award_name" placeholder="请输入奖项名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="奖项等级" prop="award_level">
                <el-select v-model="award.award_level" placeholder="请选择奖项等级" style="width: 100%">
                  <el-option label="校级" value="school" />
                  <el-option label="县级" value="county" />
                  <el-option label="市级" value="city" />
                  <el-option label="省级" value="province" />
                  <el-option label="国家级" value="national" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="获得时间" prop="date_received">
            <el-date-picker
              v-model="award.date_received"
              type="date"
              placeholder="请选择获得时间"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>

          <el-form-item label="证书照片" prop="certificate_photo">
            <div class="certificate-upload">
              <el-upload
                ref="uploadRef"
                :auto-upload="false"
                :show-file-list="false"
                accept="image/*"
                :on-change="(file) => handleCertificateChange(award, file)"
                :before-upload="beforeCertificateUpload"
              >
                <div class="upload-area">
                  <img
                    v-if="getCertificatePreview(award)"
                    :src="getCertificatePreview(award)"
                    class="certificate-preview"
                  />
                  <div v-else class="upload-placeholder">
                    <el-icon><Plus /></el-icon>
                    <div class="text">上传证书照片</div>
                    <div class="hint">支持 JPG、PNG 格式，大小不超过 5MB</div>
                  </div>
                </div>
              </el-upload>
              <el-button
                v-if="getCertificatePreview(award)"
                type="danger"
                size="small"
                @click="removeCertificate(award)"
                class="remove-btn"
              >
                删除照片
              </el-button>
            </div>
          </el-form-item>

          <el-form-item label="奖项描述" prop="award_description">
            <el-input
              v-model="award.award_description"
              type="textarea"
              placeholder="请描述获奖的背景、意义或个人感受（选填）"
              :rows="3"
            />
          </el-form-item>

          <div class="form-actions">
            <el-button @click="removeAward(index)" v-if="awardList.length > 1">
              删除
            </el-button>
          </div>
        </el-form>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-if="awardList.length === 0" class="empty-state">
      <el-empty description="暂无获奖经历">
        <el-button type="primary" @click="addAward">
          添加第一个获奖经历
        </el-button>
      </el-empty>
    </div>

    <div class="step-actions">
      <el-button @click="addAward" v-if="awardList.length > 0">
        <el-icon><Plus /></el-icon>
        添加获奖经历
      </el-button>
      <el-button type="primary" @click="handleSave" :loading="saving">
        保存获奖经历
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElMessage, type FormRules, type UploadFile } from 'element-plus'
import { awardApi, type Award } from '@/api/resume'

// Props
interface Props {
  resumeId: number
}

// Emits
interface Emits {
  (e: 'completed', completed: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const awardList = ref<Award[]>([])

// 证书照片文件映射
const certificateFiles = ref<Map<number, File>>(new Map())
const certificatePreviewUrls = ref<Map<number, string>>(new Map())

// 表单验证规则
const rules: FormRules = {
  award_name: [
    { required: true, message: '请输入奖项名称', trigger: 'blur' }
  ],
  award_level: [
    { required: true, message: '请选择奖项等级', trigger: 'change' }
  ],
  date_received: [
    { required: true, message: '请选择获得时间', trigger: 'change' }
  ]
}

// 监听获奖经历变化，判断是否完成
watch(awardList, () => {
  checkCompletion()
}, { deep: true })

// 检查完成状态
const checkCompletion = () => {
  const hasValidAward = awardList.value.some(award =>
    award.award_name && award.award_level && award.date_received
  )
  emit('completed', hasValidAward)
}

// 获取获奖经历列表
const fetchAwardList = async () => {
  loading.value = true
  try {
    const response = await awardApi.getAwardList(props.resumeId)
    const data = response.data || response

    if (data.results && data.results.length > 0) {
      awardList.value = data.results
    } else if (Array.isArray(data) && data.length > 0) {
      awardList.value = data
    } else {
      addAward()
    }
  } catch (error) {
    addAward()
  } finally {
    loading.value = false
  }
}

// 添加获奖经历
const addAward = () => {
  awardList.value.push({
    award_name: '',
    award_level: 'school',
    certificate_photo: '',
    award_description: '',
    date_received: '',
    order: awardList.value.length
  })
}

// 删除获奖经历
const removeAward = async (index: number) => {
  const award = awardList.value[index]

  if (award.id) {
    try {
      await awardApi.deleteAward(props.resumeId, award.id)
      ElMessage.success('删除成功')
    } catch (error) {
      ElMessage.error('删除失败')
      return
    }
  }

  // 清理相关的文件和预览
  if (award.id) {
    certificateFiles.value.delete(award.id)
    certificatePreviewUrls.value.delete(award.id)
  }

  awardList.value.splice(index, 1)
}

// 处理证书照片变化
const handleCertificateChange = (award: Award, file: UploadFile) => {
  if (file.raw) {
    const awardIndex = awardList.value.findIndex(a => a === award)
    const key = award.id || awardIndex

    // 保存文件对象
    certificateFiles.value.set(key, file.raw)

    // 创建预览URL
    const reader = new FileReader()
    reader.onload = (e) => {
      certificatePreviewUrls.value.set(key, e.target?.result as string)
    }
    reader.readAsDataURL(file.raw)
  }
}

// 证书上传前验证
const beforeCertificateUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('证书照片必须是图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('证书照片大小不能超过 5MB!')
    return false
  }
  return true
}

// 获取证书预览
const getCertificatePreview = (award: Award) => {
  const awardIndex = awardList.value.findIndex(a => a === award)
  const key = award.id || awardIndex

  // 优先显示新上传的预览
  if (certificatePreviewUrls.value.has(key)) {
    return certificatePreviewUrls.value.get(key)
  }

  // 显示已有的证书照片
  if (award.certificate_photo && typeof award.certificate_photo === 'string') {
    return award.certificate_photo
  }

  return null
}

// 删除证书照片
const removeCertificate = (award: Award) => {
  const awardIndex = awardList.value.findIndex(a => a === award)
  const key = award.id || awardIndex

  certificateFiles.value.delete(key)
  certificatePreviewUrls.value.delete(key)
  award.certificate_photo = ''
}

// 保存获奖经历
const handleSave = async () => {
  saving.value = true
  try {
    for (const award of awardList.value) {
      // 跳过空的获奖经历
      if (!award.award_name || !award.award_level || !award.date_received) {
        continue
      }

      const awardIndex = awardList.value.findIndex(a => a === award)
      const key = award.id || awardIndex
      const certificateFile = certificateFiles.value.get(key)

      if (certificateFile) {
        // 有新上传的证书照片，使用FormData
        const formData = new FormData()

        // 添加基本字段
        Object.keys(award).forEach(fieldKey => {
          if (fieldKey !== 'certificate_photo' && award[fieldKey] !== null && award[fieldKey] !== undefined && award[fieldKey] !== '') {
            formData.append(fieldKey, award[fieldKey])
          }
        })

        // 添加证书照片文件
        formData.append('certificate_photo', certificateFile)

        if (award.id) {
          await awardApi.updateAward(props.resumeId, award.id, formData)
        } else {
          const response = await awardApi.createAward(props.resumeId, formData)
          const data = response.data || response
          award.id = data.id
        }
      } else {
        // 没有新上传的证书照片，使用普通JSON数据
        const dataToSave = { ...award }
        // 如果没有证书照片，移除该字段避免验证错误
        if (!dataToSave.certificate_photo || dataToSave.certificate_photo === '') {
          delete dataToSave.certificate_photo
        }

        if (award.id) {
          await awardApi.updateAward(props.resumeId, award.id, dataToSave)
        } else {
          const response = await awardApi.createAward(props.resumeId, dataToSave)
          const data = response.data || response
          award.id = data.id
        }
      }
    }

    ElMessage.success('获奖经历保存成功')

    // 重新获取数据
    await fetchAwardList()

  } catch (error) {
    console.error('保存获奖经历错误:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 生命周期
onMounted(() => {
  fetchAwardList()
})
</script>

<style lang="scss" scoped>
.award-step {
  .step-header {
    margin-bottom: 32px;

    h3 {
      font-size: 24px;
      font-weight: 600;
      color: var(--text-color-primary);
      margin: 0 0 8px 0;
    }

    p {
      color: var(--text-color-secondary);
      margin: 0;
    }
  }

  .award-list {
    .award-item {
      border: 1px solid var(--border-color-light);
      border-radius: 8px;
      padding: 24px;
      margin-bottom: 20px;
      background: var(--bg-color);

      &:last-child {
        margin-bottom: 0;
      }

      .award-form {
        .certificate-upload {
          .upload-area {
            border: 2px dashed var(--border-color-light);
            border-radius: 8px;
            width: 200px;
            height: 150px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: border-color 0.3s;
            position: relative;
            overflow: hidden;

            &:hover {
              border-color: var(--color-primary);
            }

            .certificate-preview {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }

            .upload-placeholder {
              text-align: center;
              color: var(--text-color-secondary);

              .el-icon {
                font-size: 32px;
                margin-bottom: 8px;
              }

              .text {
                font-size: 14px;
                margin-bottom: 4px;
              }

              .hint {
                font-size: 12px;
                color: var(--text-color-placeholder);
              }
            }
          }

          .remove-btn {
            margin-top: 8px;
          }
        }

        .form-actions {
          text-align: right;
          margin-top: 16px;
          padding-top: 16px;
          border-top: 1px solid var(--border-color-extra-light);
        }
      }
    }
  }

  .empty-state {
    padding: 60px 0;
    text-align: center;
  }

  .step-actions {
    margin-top: 32px;
    padding-top: 24px;
    border-top: 1px solid var(--border-color-extra-light);
    display: flex;
    gap: 12px;
  }
}

@media (max-width: 768px) {
  .award-step {
    .award-list {
      .award-item {
        padding: 16px;

        .award-form {
          .certificate-upload {
            .upload-area {
              width: 150px;
              height: 120px;
            }
          }

          .el-row {
            .el-col {
              margin-bottom: 16px;
            }
          }
        }
      }
    }
  }
}
</style>
